package com.picket.controller.users.predictions;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.picket.domain.Match;
import com.picket.domain.UserPool;
import com.picket.domain.UserPrediction;
import com.picket.service.IMatchService;
import com.picket.service.IUserPoolService;
import com.picket.service.IUserPredictionService;

@Controller
@RequestMapping(value = "/users/predictions")
public class UserPredController {
/*
	@ModelAttribute("userPredForm")
	public UserPredForm createForm() {
		return new UserPredForm();
	}
*/ 
	private IMatchService matchService;
	private IUserPoolService userPoolService;
	
	@Required
	public void setUserPoolService(
			IUserPoolService userPoolService) {
		this.userPoolService = userPoolService;
	}

	@Required
	public void setMatchService(IMatchService matchService) {
		this.matchService = matchService;
	}

	private IUserPredictionService userPredService;

	@Required
	public void setUserPredictionService(IUserPredictionService userPredService) {
		this.userPredService = userPredService;
	}

	// pass the userpoolxref id. get the pool information
	// get event id from userpoolxref table
	// for now passing the event id
/*
 	@RequestMapping(value="{id}", method=RequestMethod.GET)
	public String getCreateForm(@PathVariable Long id,@ModelAttribute("userPredForm") UserPredForm userPredForm,  Model model) {
		//id is userpool id
		userPredForm.getUserPredStr().clear();
		UserPool userPool =  userPoolService.getUserPool(id) ;
		Collection<Match> matches = matchService.getAllMatchesForEvent(userPool.getEventId());
		Collection<Match> toBePredictedMatches = new ArrayList<Match>();
		Calendar currentDateTime = Calendar.getInstance();
		for(Match match:matches){
			if(!isHistory(currentDateTime.getTime(),match.getMatchDateTime())){
				toBePredictedMatches.add(match);
			}
		}
		model.addAttribute("matches", toBePredictedMatches);
		
		
//		model.addAttribute("userPredForm", userPredService.getAllUserPredictionsForUserPool(id));
		userPredForm.initialize((ArrayList<UserPrediction>)userPredService.getAllUserPredictionsForUserPoolOrderedByMatchNo(id));
		userPredForm.setUserPoolId(id);
		model.addAttribute("userPoolId", id);
		model.addAttribute("userPredForm", userPredForm);
		return "/users/predictions/createForm";
	}
*/	

	
 	@RequestMapping(value="{id}", method=RequestMethod.GET)
	public String getCreateForm(@PathVariable Long id,@ModelAttribute("userPredForm") UserPredForm userPredForm,  Model model) {
		
 		//id passed is userpool id
 		
 		// init
 		Collection<Match> toBePredictedMatches = new ArrayList<Match>();
 		
 		//initialize the form to clear string
		userPredForm.clearData();
		
		// get the user pool information to get the event id
		UserPool userPool =  userPoolService.getUserPool(id);
		
		// Get all Matches for the event
		ArrayList<Match> matches = (ArrayList<Match>)matchService.getAllMatchesForEvent(userPool.getEventId());
		ArrayList<UserPrediction> userPredList = (ArrayList<UserPrediction>)userPredService.getAllUserPredictionsForUserPoolOrderedByMatchNo(id);
		Assert.isTrue(matches.size()==userPredList.size(), "Server Error: Match Size and Pred Size do not match.Please Retry the request.");
		
		for(int i=0; i<matches.size();i++){
			Match match = (Match)matches.get(i);
			UserPrediction userPred = (UserPrediction) userPredList.get(i);
			
			Calendar currentDateTime = Calendar.getInstance();
			
			if(isHistory(currentDateTime.getTime(),match.getMatchDateTime())){
				userPredForm.getHistory().add(userPred);
				
			}else{
				userPredForm.getToBePredicted().add(userPred);
				userPredForm.getUserPredStr().add(userPred.getMatchPrediction());
				toBePredictedMatches.add(match);
			}
		}
	
		model.addAttribute("matches", toBePredictedMatches);
		userPredForm.setUserPoolId(id);
		model.addAttribute("userPoolId", id);
		model.addAttribute("userPredForm", userPredForm);
		return "/users/predictions/createForm";
	}

 	
	private boolean isHistory(Date currentDateTime,
			Date matchDateTimeAsCalendar) {
		//return  currentDateTime.after(matchDateTimeAsCalendar);
		Calendar matchDate = Calendar.getInstance();
		matchDate.setTime(matchDateTimeAsCalendar);
		Calendar current = Calendar.getInstance();
		matchDate.add(Calendar.MINUTE, -30);
		return  current.after(matchDate);
	}
	
	
	@RequestMapping(method = RequestMethod.POST)
	public String create( @ModelAttribute("userPredForm") UserPredForm userPredForm, BindingResult result,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,  Model model) throws Exception {
		userPredService.updatePredictions(userPredForm.userPredStr,userPredForm.getUserPoolId());

		
		List<UserPrediction> currPreds = new ArrayList<UserPrediction>();
		List<UserPrediction> histPreds = new ArrayList<UserPrediction>();
		
		
		ArrayList<UserPrediction> userPredList = (ArrayList<UserPrediction>)userPredService.getAllUserPredictionsForUserPoolOrderedByMatchNo(userPredForm.getUserPoolId());
		
		for(int i=0; i<userPredList.size();i++){
			UserPrediction userPred = (UserPrediction) userPredList.get(i);
			
			Calendar currentDateTime = Calendar.getInstance();
			
			if(isHistory(currentDateTime.getTime(),userPred.getMatchDateTime())){
				histPreds.add(userPred);
				
			}else{
				currPreds.add(userPred);
			}
		}
		
		
		model.addAttribute("currPreds", currPreds);
		model.addAttribute("userPoolId", userPredForm.getUserPoolId());
		model.addAttribute("histPreds", histPreds);
		
		return "/users/predictions/viewResult";
	}
	/*
	@RequestMapping(method = RequestMethod.POST)
	public String create( @ModelAttribute("userPredForm") UserPredForm userPredForm, BindingResult result,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,  Model model) throws Exception {
		System.out.println("");
		ArrayList<UserPrediction> preds = (ArrayList<UserPrediction>)userPredService.updatePredictions(userPredForm.userPredStr,userPredForm.getUserPoolId());
		userPredForm.getUserPredStr().clear();
		userPredForm.initialize(preds);
		
		userPredForm.setUserPoolId(userPredForm.getUserPoolId());
		model.addAttribute("userPoolId",userPredForm.getUserPoolId());
		model.addAttribute("userPredForm", userPredForm);
		//return "/users/predictions/createForm";
		return "redirect:predictions/"+userPredForm.getUserPoolId();
	}
	 */
/*	
	@RequestMapping(value="all", method=RequestMethod.GET)
	public String getView( Model model) {
		Collection<Team> teams = teamService.getAllTeams();

		model.addAttribute("teams", teams);
		return "teams/view";
	}
*/	
}